﻿#region License

// Created by John Batte on 03/22/2012 at 7:49 AM.
// Last code cleanup: 03/22/2012 at 8:02 AM.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using BatteCode.Fx.ExceptionHandling;

namespace BatteCode.Fx.Collections
{
	/// <summary>
	/// 	Defines extensions to the collection types.
	/// </summary>
	public static class CollectionExtensions
	{
		/// <summary>
		/// 	Adds the range of items.
		/// </summary>
		/// <typeparam name="T"> </typeparam>
		/// <param name="items"> The items. </param>
		/// <param name="newItems"> The new items. </param>
		public static void AddRange<T>(this ICollection<T> items, IEnumerable<T> newItems)
		{
			foreach (T item in newItems) items.Add(item);
		}

		/// <summary>
		/// 	Runs the specified action against each item in the set.
		/// </summary>
		/// <typeparam name="T"> The item type. </typeparam>
		/// <param name="items"> The items. </param>
		/// <param name="action"> The action. </param>
		/// <param name="parallel"> If set to <c>true</c> , run the action across the set in parallel. The default is <c>false</c> . </param>
		/// <param name="errorHandler"> The error handler (optional). </param>
		/// <remarks>
		/// 	If the <paramref name="parallel" /> parameter is set to <c>true</c> , the <see cref="Parallel" /> class is used to execute asynchronous <see
		///  	cref="Task" /> objects agsinst the set. See <see cref="System.Threading.Tasks" /> for details. <br /> Error handling is provided by <see
		///  	cref="Try.HandleErrors.DefaultStrategy" /> if no error handler is specified.
		/// </remarks>
		/// <seealso cref="Try" />
		public static void Each<T>(this IEnumerable<T> items, Action<T> action, bool parallel = false, Func<Exception, ExceptionState> errorHandler = null)
		{
			if (parallel) Parallel.ForEach(items, item => Try.Do(() => action(item), errorHandler));
			else
			{
				foreach (T item in items)
				{
					T currentItem = item;
					Try.Do(() => action(currentItem), errorHandler);
				}
			}
		}
	}
}